<template>
  <div ref="actionsRef" class="je-admin-top-actions">
    <SecuritySystem />
    <GlobalSearch v-if="actions?.includes('SEARCH')" ref="searchRef" />
    <div
      v-for="(action, index) in actionInfo"
      :key="index"
      :class="['action', 'action-' + action.code.toLocaleLowerCase()]"
      @click="(event) => actionClick(action, event)"
    >
      <Tooltip placement="bottom" :title="action.text">
        <Badge :count="action.badge" :offset="[0, 10]" dot>
          <i :class="['action-icon', 'fal', action.icon]"
        /></Badge>
      </Tooltip>
    </div>
    <Setting v-if="setting" class="action" />
    <Popover
      v-if="![LayoutType.APP, LayoutType.SINGLE].includes($route.params.layout)"
      placement="bottomRight"
      trigger="click"
      :visible="showPrevHistoryMenu"
      :overlay-class-name="'settings-prev-history-menu-popover'"
      :overlay-inner-style="{ padding: 0 }"
      @visible-change="showPrevHistoryMenu = false"
    >
      <div class="settings-prev-history-menu-p"></div>
      <template #content>
        <div class="settings-prev-history-menu">
          <div class="title">{{ $t('settings.historyConfirm') }}</div>
          <div class="buttons">
            <div class="button primary" @click="recoverPrevHistoryMenus()">
              {{ $t('settings.historyConfirmOk') }}
            </div>
            <div class="button" @click="recoverPrevHistoryMenus(false)">
              {{ $t('settings.historyConfirmCancel') }}
            </div>
          </div>
        </div>
      </template>
    </Popover>
  </div>
</template>
<script>
  import { defineComponent, computed, reactive, onMounted, ref, nextTick } from 'vue';
  import { useAdminStore } from '@/stores/admin-store';
  import { Tooltip, Badge } from 'ant-design-vue';
  import Setting from './settings/index.vue';
  import { doUpdateSign, loadReadSign } from './settings/api/index';
  import { getCurrentUser } from '@jecloud/utils';
  import { useWebSocketStore } from '@/stores/websocket-store';
  import { Modal, Popover } from '@jecloud/ui';
  import { useMenuStore } from '@/stores/menu-store';
  import { LayoutType } from '@/data/enum/layout';
  import { useRoute } from 'vue-router';
  import SecuritySystem from './security/security-system';
  import GlobalSearch from '@/views/menus/search/global-search.vue';
  export default defineComponent({
    name: 'AdminTopMenuActions',
    components: {
      Popover,
      Tooltip,
      Badge,
      Setting,
      SecuritySystem,
      GlobalSearch,
    },
    props: {
      actions: {
        type: Array,
        default: () => [],
      },
      setting: { type: Boolean, default: true },
    },
    setup(props, { expose }) {
      const adminStore = useAdminStore();
      const menuStore = useMenuStore();
      const actionsRef = ref();
      const searchRef = ref();
      const showPrevHistoryMenu = ref(false);
      const route = useRoute();
      const actions = reactive({
        SEARCH: { icon: 'fa-search', text: '搜索', badge: 0, code: 'SEARCH' },
        WF: { icon: 'fa-sitemap', text: '待我审批', badge: 0, code: 'WF' },
        MSG: { icon: 'fa-bell', text: '通知', badge: 0, code: 'MSG' },
        mail: { icon: 'fa-envelope', text: '微邮', badge: 0, code: 'mail' },
        postil: { icon: 'fa-bookmark', text: '批注', badge: 0, code: 'postil' },
      });
      const actionInfo = computed(() => {
        return props.actions.map((action) => actions[action]);
      });
      const webSocketStore = useWebSocketStore();
      const actionClick = (item, event) => {
        switch (item.code) {
          case 'WF':
          case 'MSG':
            doUpdateSign({
              userId: getCurrentUser().id,
              deptId: getCurrentUser().organization.id,
              actionType: 'doUpdate',
              pushType: item.code,
            })
              .then(() => {
                actions[item.code].badge = 0;
              })
              .catch((error) => {
                Modal.alert(error.message, 'error');
              });
            adminStore.emitMicro('JE_CORE_BOARDS_INIT', 'home-init-board', {
              type: item.code,
            });
            break;
          case 'SEARCH':
            searchRef.value.show({ event });
            break;
        }
      };
      // 获取右上角小红点的数据
      const getNoReadCount = () => {
        const params = {
          userId: getCurrentUser().id,
          deptId: getCurrentUser().organization.id,
          pushType: 'MSG,WF',
        };
        loadReadSign(params)
          .then((data) => {
            const keyArr = Object.keys(data);
            if (keyArr.length) {
              keyArr.forEach((key) => {
                actions[key].badge = parseInt(data[key]);
              });
            }
          })
          .catch((error) => {
            Modal.alert(error.message, 'error');
          });
      };
      // 恢复历史菜单
      const recoverPrevHistoryMenus = (recover = true) => {
        if (recover) {
          menuStore.openMenus = menuStore.prevHistoryMenus.concat(
            menuStore.openMenus.filter((id) => !menuStore.prevHistoryMenus.includes(id)),
          );
          menuStore.activeSiderMenu = menuStore.openMenus[0];
        } else {
          menuStore.clearPrevHistoryMenus();
        }
        showPrevHistoryMenu.value = false;
      };
      onMounted(() => {
        nextTick(() => {
          getNoReadCount();
          // 恢复历史菜单
          menuStore
            .recoverPrevHistoryMenus()
            .then((ids) => {
              const currentMenuId = route.params.menu;
              showPrevHistoryMenu.value =
                ids.length > 1 || (ids.length === 1 && ids[0] != currentMenuId);
            })
            .catch(() => {
              showPrevHistoryMenu.value = false;
            });
        });
      });
      webSocketStore.on('message', (message) => {
        if (!message || !message.busType) return false;
        const type = message.busType.indexOf('MSG') >= 0 ? 'MSG' : message.busType;
        if (actions[type]) {
          actions[type].badge = 1;
        }
      });
      expose({
        getSize() {
          return actionsRef.value?.offsetWidth;
        },
      });
      return {
        actionInfo,
        actionClick,
        getNoReadCount,
        actionsRef,
        searchRef,
        recoverPrevHistoryMenus,
        showPrevHistoryMenu,
        LayoutType,
      };
    },
  });
</script>
<style lang="less">
  .je-admin-top-actions {
    display: inline-flex;
    justify-content: flex-end;
    .action {
      padding: 0 10px;
      display: inline-flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      &-icon {
        font-size: 14px;
        line-height: 30px;
      }
    }
    .settings-prev-history-menu-p {
      position: absolute;
      right: 30px;
      bottom: 12px;
      width: 20px;
      height: 20px;
      z-index: -1;
    }
  }
  .settings-prev-history-menu-popover {
    .ant-popover-inner-content {
      padding: 0;
    }
  }
  .settings-prev-history-menu {
    width: 240px;
    text-align: center;
    .title {
      padding: 12px 0;
    }
    .buttons {
      display: flex;
      align-items: center;
      justify-content: center;
      border-top: 1px solid #f2f2f2;
      .button {
        cursor: pointer;
        padding: 6px;
        flex: 1;
        &.primary {
          color: @primary-color;
          border-right: 1px solid #f2f2f2;
        }
      }
    }
  }
</style>
